from datetime import datetime, time, timedelta
from typing import List, Dict, Any, Optional
import logging
from django.db.models import Q
from ..models import Event

logger = logging.getLogger('apps')

class ConflictService:
    """日程冲突检测与智能解决服务"""
    
    def __init__(self):
        # 常用时间段，用于智能推荐
        self.common_time_slots = [
            '08:00', '08:30', '09:00', '09:30', '10:00', '10:30', '11:00', '11:30',
            '14:00', '14:30', '15:00', '15:30', '16:00', '16:30', '17:00', '17:30'
        ]
        # 最小调整时间（分钟）
        self.min_adjustment = 30
        
        # 新增：日程类型分类与时间偏好模型
        self.event_type_preferences = {
            # 运动类活动
            'morning_exercise': {
                'keywords': ['晨跑', '晨练', '早操', '晨跑步', '早起跑步', '早起锻炼'],
                'preferred_periods': ['early_morning'],
                'preferred_slots': ['06:00-07:00', '06:30-07:30', '07:00-08:00'],
                'avoid_periods': ['afternoon', 'evening'],
                'description': '晨练活动'
            },
            'workout': {
                'keywords': ['健身', '锻炼', '运动', '健身房', '力量训练', '有氧运动', '跑步', '慢跑'],
                'preferred_periods': ['evening', 'late_afternoon'],
                'preferred_slots': ['17:00-18:30', '18:00-19:30', '19:00-20:30'],
                'avoid_periods': ['early_morning', 'morning'],
                'description': '健身锻炼'
            },
            'sports': {
                'keywords': ['打球', '篮球', '足球', '排球', '羽毛球', '乒乓球', '网球', '游泳'],
                'preferred_periods': ['evening', 'late_afternoon', 'weekend_morning'],
                'preferred_slots': ['16:00-18:00', '18:00-20:00', '19:00-21:00'],
                'avoid_periods': ['early_morning', 'noon'],
                'description': '球类运动'
            },
            
            # 学习类活动
            'class': {
                'keywords': ['课', '课程', '上课', '听课', '讲座', '报告', '研讨会'],
                'preferred_periods': ['morning', 'afternoon'],
                'preferred_slots': ['08:00-12:00', '14:00-17:00'],
                'avoid_periods': ['evening', 'early_morning'],
                'description': '课程学习'
            },
            'study': {
                'keywords': ['自习', '学习', '复习', '预习', '做作业', '写论文', '看书', '读书'],
                'preferred_periods': ['morning', 'afternoon', 'evening'],
                'preferred_slots': ['09:00-11:30', '14:00-17:00', '19:00-22:00'],
                'avoid_periods': ['early_morning', 'late_night'],
                'description': '自主学习'
            },
            'library': {
                'keywords': ['图书馆', '自习室', '阅览室'],
                'preferred_periods': ['morning', 'afternoon', 'evening'],
                'preferred_slots': ['09:00-11:30', '14:00-17:00', '19:00-22:00'],
                'avoid_periods': ['early_morning'],
                'description': '图书馆学习'
            },
            
            # 社交类活动
            'meeting': {
                'keywords': ['会议', '开会', '碰头会', '组会', '班会', '例会'],
                'preferred_periods': ['morning', 'afternoon'],
                'preferred_slots': ['10:00-11:30', '14:00-16:00'],
                'avoid_periods': ['early_morning', 'evening'],
                'description': '会议'
            },
            'social': {
                'keywords': ['聚会', '聚餐', '约饭', '聚', '派对', '社交', '交友'],
                'preferred_periods': ['evening', 'noon'],
                'preferred_slots': ['11:30-13:00', '18:00-20:00', '19:00-21:00'],
                'avoid_periods': ['early_morning', 'morning'],
                'description': '社交活动'
            },
            
            # 生活类活动
            'meal': {
                'keywords': ['吃饭', '午饭', '晚饭', '早饭', '早餐', '午餐', '晚餐', '用餐'],
                'preferred_periods': ['early_morning', 'noon', 'evening'],
                'preferred_slots': ['07:00-08:00', '11:30-13:00', '17:30-19:00'],
                'avoid_periods': ['morning', 'afternoon'],
                'description': '用餐时间'
            },
            'rest': {
                'keywords': ['休息', '午休', '小憩', '睡觉', '睡午觉', '午睡'],
                'preferred_periods': ['noon'],
                'preferred_slots': ['12:00-14:00'],
                'avoid_periods': ['morning', 'afternoon', 'evening'],
                'description': '休息时间'
            },
            'entertainment': {
                'keywords': ['娱乐', '看电影', '看剧', '游戏', '玩游戏', 'KTV', '唱歌', '逛街', '购物'],
                'preferred_periods': ['evening', 'weekend_afternoon'],
                'preferred_slots': ['19:00-22:00', '14:00-17:00'],
                'avoid_periods': ['early_morning', 'morning'],
                'description': '娱乐活动'
            }
        }
        
        # 时间段定义
        self.time_periods = {
            'early_morning': {'start': '06:00', 'end': '08:00', 'description': '早晨'},
            'morning': {'start': '08:00', 'end': '11:30', 'description': '上午'},
            'noon': {'start': '11:30', 'end': '14:00', 'description': '中午'},
            'afternoon': {'start': '14:00', 'end': '17:00', 'description': '下午'},
            'late_afternoon': {'start': '17:00', 'end': '19:00', 'description': '傍晚'},
            'evening': {'start': '19:00', 'end': '22:00', 'description': '晚上'},
            'late_night': {'start': '22:00', 'end': '23:59', 'description': '深夜'},
            'weekend_morning': {'start': '09:00', 'end': '12:00', 'description': '周末上午'},
            'weekend_afternoon': {'start': '14:00', 'end': '18:00', 'description': '周末下午'}
        }

    def _time_to_minutes(self, time_val) -> int:
        """将时间值转换为分钟数"""
        try:
            if isinstance(time_val, str):
                hours, minutes = map(int, time_val.split(':'))
                return hours * 60 + minutes
            elif isinstance(time_val, time):
                return time_val.hour * 60 + time_val.minute
            else:
                logger.error(f"不支持的时间格式: {type(time_val)}")
                return 0
        except Exception as e:
            logger.error(f"时间转换失败: {str(e)}")
            return 0

    def _minutes_to_time(self, minutes: int) -> str:
        """将分钟数转换为时间字符串 HH:MM"""
        hours = minutes // 60
        mins = minutes % 60
        return f"{hours:02d}:{mins:02d}"

    def _format_time(self, time_val) -> str:
        """格式化时间值为字符串"""
        if isinstance(time_val, str):
            return time_val
        elif isinstance(time_val, time):
            return time_val.strftime('%H:%M')
        else:
            logger.error(f"不支持的时间格式: {type(time_val)}")
            return "00:00"

    def _get_conflict_duration(self, event1, event2) -> int:
        """计算两个日程的重叠时间（分钟）"""
        try:
            start1 = self._time_to_minutes(event1['start_time'])
            end1 = self._time_to_minutes(event1['end_time'])
            start2 = self._time_to_minutes(event2['start_time'])
            end2 = self._time_to_minutes(event2['end_time'])

            overlap_start = max(start1, start2)
            overlap_end = min(end1, end2)
            return max(0, overlap_end - overlap_start)
        except Exception as e:
            logger.error(f"计算冲突时长失败: {str(e)}")
            return 0

    def _get_event_duration(self, event) -> int:
        """获取日程持续时间（分钟）"""
        try:
            start = self._time_to_minutes(event['start_time'])
            end = self._time_to_minutes(event['end_time'])
            return max(0, end - start)
        except Exception as e:
            logger.error(f"计算日程时长失败: {str(e)}")
            return 60  # 默认1小时

    def _find_available_slots(self, date, existing_events, duration_minutes, 
                             preferred_start=None, preferred_end=None) -> List[Dict]:
        """查找可用的时间段
        
        Args:
            date: 日期
            existing_events: 当天已有的日程
            duration_minutes: 需要的时长（分钟）
            preferred_start: 偏好的开始时间（可选）
            preferred_end: 偏好的结束时间（可选）
            
        Returns:
            可用时间段列表，按照与偏好时间的接近程度排序
        """
        # 过滤出当天的事件
        day_events = [e for e in existing_events if str(e.get('date', '')) == str(date)]
        
        # 按开始时间排序
        day_events.sort(key=lambda x: self._time_to_minutes(x['start_time']))
        
        # 工作时间范围（分钟）：8:00 - 18:00
        work_start = 8 * 60
        work_end = 18 * 60
        
        # 构建被占用的时间段
        occupied_slots = []
        for event in day_events:
            start = self._time_to_minutes(event['start_time'])
            end = self._time_to_minutes(event['end_time'])
            occupied_slots.append((start, end))
        
        # 合并重叠的时间段
        if occupied_slots:
            occupied_slots.sort()
            merged = [occupied_slots[0]]
            for current in occupied_slots[1:]:
                prev = merged[-1]
                if current[0] <= prev[1]:
                    # 有重叠，合并
                    merged[-1] = (prev[0], max(prev[1], current[1]))
                else:
                    # 无重叠，添加新区间
                    merged.append(current)
            occupied_slots = merged
        
        # 查找可用时间段
        available_slots = []
        
        # 添加工作开始时间到第一个事件之间的时间段
        if not occupied_slots or occupied_slots[0][0] > work_start:
            first_event_start = occupied_slots[0][0] if occupied_slots else work_end
            if first_event_start - work_start >= duration_minutes:
                available_slots.append({
                    'start': self._minutes_to_time(work_start),
                    'end': self._minutes_to_time(work_start + duration_minutes),
                    'type': 'morning'
                })
        
        # 添加事件之间的空闲时间段
        for i in range(len(occupied_slots)):
            current_end = occupied_slots[i][1]
            next_start = occupied_slots[i+1][0] if i < len(occupied_slots)-1 else work_end
            
            if next_start - current_end >= duration_minutes:
                available_slots.append({
                    'start': self._minutes_to_time(current_end),
                    'end': self._minutes_to_time(current_end + duration_minutes),
                    'type': 'between'
                })
        
        # 如果有偏好时间，按照与偏好时间的接近程度排序
        if preferred_start:
            pref_minutes = self._time_to_minutes(preferred_start)
            for slot in available_slots:
                slot_minutes = self._time_to_minutes(slot['start'])
                slot['distance'] = abs(slot_minutes - pref_minutes)
            
            available_slots.sort(key=lambda x: x['distance'])
        
        return available_slots

    def generate_smart_suggestions(self, new_event, existing_events) -> List[Dict]:
        """为冲突的日程生成智能调整建议
        
        Args:
            new_event: 新日程
            existing_events: 已有日程列表
            
        Returns:
            建议列表，包含调整方案
        """
        try:
            # 获取与新日程冲突的事件
            conflicts = []
            for event in existing_events:
                if str(event.get('date', '')) == str(new_event.get('date', '')) and \
                   self._get_conflict_duration(new_event, event) > 0:
                    conflicts.append(event)
            
            if not conflicts:
                return []
            
            # 使用优化后的方法生成建议
            logger.info(f"使用优化后的方法生成建议，冲突数量: {len(conflicts)}")
            return self.generate_conflict_solutions(new_event, conflicts, existing_events)
            
        except Exception as e:
            logger.error(f"生成智能建议失败: {str(e)}")
            return []

    def _time_overlap(self, event1, event2) -> bool:
        """检查两个事件的时间是否重叠"""
        start1 = self._time_to_minutes(event1['start_time'])
        end1 = self._time_to_minutes(event1['end_time'])
        start2 = self._time_to_minutes(event2['start_time'])
        end2 = self._time_to_minutes(event2['end_time'])
        
        return max(start1, start2) < min(end1, end2)

    def check_conflicts(self, user, events_data: List[Dict[str, Any]]) -> Dict[str, Any]:
        """检查日程冲突并提供智能建议
        
        Args:
            user: 用户对象
            events_data: 日程数据列表
            
        Returns:
            冲突检测结果，包含智能建议
        """
        conflicts = []
        total_conflicts = 0
        
        try:
            # 获取日期范围内的所有已存在的日程
            dates = set(event['date'] for event in events_data)
            existing_events = Event.objects.filter(
                user=user,
                date__in=dates
            ).values('id', 'title', 'date', 'start_time', 'end_time', 'importance')
            
            # 将现有日程按日期分组
            existing_by_date = {}
            for event in existing_events:
                date = str(event['date'])
                if date not in existing_by_date:
                    existing_by_date[date] = []
                # 确保时间格式统一
                event_copy = dict(event)
                event_copy['start_time'] = self._format_time(event['start_time'])
                event_copy['end_time'] = self._format_time(event['end_time'])
                existing_by_date[date].append(event_copy)
            
            # 检查每个新日程的冲突
            for i, new_event in enumerate(events_data):
                date = new_event['date']
                if date in existing_by_date:
                    date_conflicts = []
                    
                    for existing_event in existing_by_date[date]:
                        # 计算重叠时间
                        overlap = self._get_conflict_duration(new_event, existing_event)
                        
                        if overlap > 0:
                            # 计算冲突严重程度
                            new_event_duration = self._get_event_duration(new_event)
                            existing_event_duration = self._get_event_duration(existing_event)
                            
                            # 计算重叠比例
                            new_overlap_ratio = overlap / new_event_duration if new_event_duration > 0 else 0
                            existing_overlap_ratio = overlap / existing_event_duration if existing_event_duration > 0 else 0
                            
                            # 确定冲突严重程度
                            severity = "low"
                            if new_overlap_ratio > 0.75 or existing_overlap_ratio > 0.75:
                                severity = "high"
                            elif new_overlap_ratio > 0.3 or existing_overlap_ratio > 0.3:
                                severity = "medium"
                            
                            # 为这个冲突生成智能建议
                            suggestions = self.generate_smart_suggestions(
                                new_event, 
                                existing_by_date[date]
                            )
                            
                            # 添加索引，便于前端定位
                            new_event_with_index = {
                                'title': new_event['title'],
                                'date': new_event['date'],
                                'start_time': new_event['start_time'],
                                'end_time': new_event['end_time'],
                                'index': i  # 添加索引
                            }
                            
                            # 计算冲突时间段的具体时间
                            new_start = self._time_to_minutes(new_event['start_time'])
                            new_end = self._time_to_minutes(new_event['end_time'])
                            existing_start = self._time_to_minutes(existing_event['start_time'])
                            existing_end = self._time_to_minutes(existing_event['end_time'])
                            
                            overlap_start = max(new_start, existing_start)
                            overlap_end = min(new_end, existing_end)
                            
                            conflict_info = {
                                'type': 'external',  # 标记为外部冲突
                                'new_event': new_event_with_index,
                                'existing_event': {
                                    'id': existing_event['id'],
                                    'title': existing_event['title'],
                                    'date': str(existing_event['date']),
                                    'start_time': existing_event['start_time'],
                                    'end_time': existing_event['end_time'],
                                    'importance': existing_event['importance']
                                },
                                'overlap_minutes': overlap,
                                'overlap_ratio': round(new_overlap_ratio * 100, 1),  # 百分比形式
                                'overlap_period': {
                                    'start': self._minutes_to_time(overlap_start),
                                    'end': self._minutes_to_time(overlap_end)
                                },
                                'severity': severity,
                                'suggestions': suggestions
                            }
                            date_conflicts.append(conflict_info)
                            total_conflicts += 1
                    
                    if date_conflicts:
                        conflicts.append({
                            'date': date,
                            'conflicts': date_conflicts,
                            'type': 'external'  # 标记为外部冲突
                        })
            
            # 新增：检测待创建日程之间的冲突
            internal_conflicts = self._check_internal_conflicts(events_data)
            
            # 合并两种冲突结果
            if internal_conflicts['has_conflicts']:
                conflicts.extend(internal_conflicts['conflicts'])
                total_conflicts += internal_conflicts['conflict_count']
            
            # 计算整体冲突严重程度
            overall_severity = "low"
            if total_conflicts > 0:
                high_severity_count = 0
                medium_severity_count = 0
                
                for date_conflict in conflicts:
                    for conflict in date_conflict['conflicts']:
                        if conflict['severity'] == "high":
                            high_severity_count += 1
                        elif conflict['severity'] == "medium":
                            medium_severity_count += 1
                
                if high_severity_count > 0:
                    overall_severity = "high"
                elif medium_severity_count > 0:
                    overall_severity = "medium"
            
            return {
                'has_conflicts': total_conflicts > 0,
                'conflict_count': total_conflicts,
                'overall_severity': overall_severity,
                'conflicts': conflicts,
                'has_internal_conflicts': internal_conflicts['has_conflicts'],
                'has_external_conflicts': len(conflicts) > len(internal_conflicts['conflicts']) if internal_conflicts['has_conflicts'] else total_conflicts > 0
            }
            
        except Exception as e:
            logger.error(f"检查日程冲突失败: {str(e)}")
            return {
                'has_conflicts': False,
                'conflict_count': 0,
                'overall_severity': "none",
                'conflicts': [],
                'has_internal_conflicts': False,
                'has_external_conflicts': False
            }
    
    def _check_internal_conflicts(self, events_data: List[Dict[str, Any]]) -> Dict[str, Any]:
        """检查待创建日程之间的冲突"""
        conflicts = []
        total_conflicts = 0
        
        try:
            # 按日期分组
            events_by_date = {}
            for i, event in enumerate(events_data):
                date = str(event['date'])
                if date not in events_by_date:
                    events_by_date[date] = []
                
                # 添加索引，便于后续处理
                event_copy = dict(event)
                event_copy['index'] = i
                events_by_date[date].append(event_copy)
            
            # 检查每个日期内的日程冲突
            for date, date_events in events_by_date.items():
                date_conflicts = []
                
                # 比较每对日程
                for i in range(len(date_events)):
                    for j in range(i+1, len(date_events)):
                        event1 = date_events[i]
                        event2 = date_events[j]
                        
                        # 计算重叠时间
                        overlap = self._get_conflict_duration(event1, event2)
                        
                        if overlap > 0:
                            # 计算冲突严重程度
                            event1_duration = self._get_event_duration(event1)
                            event2_duration = self._get_event_duration(event2)
                            
                            # 计算重叠比例
                            event1_overlap_ratio = overlap / event1_duration if event1_duration > 0 else 0
                            event2_overlap_ratio = overlap / event2_duration if event2_duration > 0 else 0
                            
                            # 确定冲突严重程度
                            severity = "low"
                            if event1_overlap_ratio > 0.75 or event2_overlap_ratio > 0.75:
                                severity = "high"
                            elif event1_overlap_ratio > 0.3 or event2_overlap_ratio > 0.3:
                                severity = "medium"
                            
                            # 计算冲突时间段
                            event1_start = self._time_to_minutes(event1['start_time'])
                            event1_end = self._time_to_minutes(event1['end_time'])
                            event2_start = self._time_to_minutes(event2['start_time'])
                            event2_end = self._time_to_minutes(event2['end_time'])
                            
                            overlap_start = max(event1_start, event2_start)
                            overlap_end = min(event1_end, event2_end)
                            
                            # 为这个内部冲突生成智能建议
                            # 注意：这里需要特殊处理，确保两个日程的建议不同
                            suggestions1 = self._generate_internal_conflict_suggestions(event1, event2, date_events)
                            suggestions2 = self._generate_internal_conflict_suggestions(event2, event1, date_events)
                            
                            # 添加冲突信息
                            conflict_info = {
                                'type': 'internal',  # 标记为内部冲突
                                'event1': {
                                    'index': event1['index'],
                                    'title': event1['title'],
                                    'date': date,
                                    'start_time': event1['start_time'],
                                    'end_time': event1['end_time']
                                },
                                'event2': {
                                    'index': event2['index'],
                                    'title': event2['title'],
                                    'date': date,
                                    'start_time': event2['start_time'],
                                    'end_time': event2['end_time']
                                },
                                'overlap_minutes': overlap,
                                'overlap_ratio1': round(event1_overlap_ratio * 100, 1),
                                'overlap_ratio2': round(event2_overlap_ratio * 100, 1),
                                'overlap_period': {
                                    'start': self._minutes_to_time(overlap_start),
                                    'end': self._minutes_to_time(overlap_end)
                                },
                                'severity': severity,
                                'suggestions1': suggestions1,  # 第一个日程的建议
                                'suggestions2': suggestions2   # 第二个日程的建议
                            }
                            
                            date_conflicts.append(conflict_info)
                            total_conflicts += 1
                
                if date_conflicts:
                    conflicts.append({
                        'date': date,
                        'conflicts': date_conflicts,
                        'type': 'internal'  # 标记为内部冲突
                    })
            
            # 计算整体冲突严重程度
            overall_severity = "low"
            if total_conflicts > 0:
                high_severity_count = 0
                medium_severity_count = 0
                
                for date_conflict in conflicts:
                    for conflict in date_conflict['conflicts']:
                        if conflict['severity'] == "high":
                            high_severity_count += 1
                        elif conflict['severity'] == "medium":
                            medium_severity_count += 1
                
                if high_severity_count > 0:
                    overall_severity = "high"
                elif medium_severity_count > 0:
                    overall_severity = "medium"
            
            return {
                'has_conflicts': total_conflicts > 0,
                'conflict_count': total_conflicts,
                'overall_severity': overall_severity,
                'conflicts': conflicts
            }
            
        except Exception as e:
            logger.error(f"检查内部日程冲突失败: {str(e)}")
            return {
                'has_conflicts': False,
                'conflict_count': 0,
                'overall_severity': "none",
                'conflicts': []
            }
    
    def _generate_internal_conflict_suggestions(self, event, conflicting_event, all_events):
        """为内部冲突生成智能建议，确保不同日程有不同的建议"""
        suggestions = []
        
        try:
            # 获取日程持续时间
            duration = self._get_event_duration(event)
            if duration <= 0:
                return suggestions
            
            # 1. 调整时间建议 - 错开时间
            # 为第一个事件提前，为第二个事件推后
            event_index = event['index']
            conflict_index = conflicting_event['index']
            
            if event_index < conflict_index:
                # 第一个事件提前
                conflict_start = self._time_to_minutes(conflicting_event['start_time'])
                event_start = self._time_to_minutes(event['start_time'])
                
                # 提前结束
                if event_start < conflict_start:
                    new_end = self._minutes_to_time(conflict_start)
                    actual_duration = conflict_start - event_start
                    
                    if actual_duration >= 30:  # 确保至少30分钟
                        suggestions.append({
                            'type': 'shorten',
                            'start_time': event['start_time'],
                            'end_time': new_end,
                            'description': f"提前在 {new_end} 结束，持续{actual_duration//60}小时{actual_duration%60}分钟，避开「{conflicting_event['title']}」"
                        })
                
                # 提前开始
                early_start = event_start - 60  # 提前1小时
                if early_start >= 8 * 60:  # 不早于8:00
                    new_start = self._minutes_to_time(early_start)
                    new_end = self._minutes_to_time(early_start + duration)
                    
                    suggestions.append({
                        'type': 'reschedule',
                        'start_time': new_start,
                        'end_time': new_end,
                        'description': f"调整到 {new_start}-{new_end}，避开「{conflicting_event['title']}」"
                    })
            else:
                # 第二个事件推后
                conflict_end = self._time_to_minutes(conflicting_event['end_time'])
                event_end = self._time_to_minutes(event['end_time'])
                
                # 延后开始
                if event_end > conflict_end:
                    new_start = self._minutes_to_time(conflict_end)
                    actual_duration = event_end - conflict_end
                    
                    if actual_duration >= 30:  # 确保至少30分钟
                        suggestions.append({
                            'type': 'shorten',
                            'start_time': new_start,
                            'end_time': event['end_time'],
                            'description': f"延后到 {new_start} 开始，持续{actual_duration//60}小时{actual_duration%60}分钟，避开「{conflicting_event['title']}」"
                        })
                
                # 推后结束
                late_start = conflict_end
                late_end = late_start + duration
                
                if late_end <= 20 * 60:  # 不晚于20:00
                    new_start = self._minutes_to_time(late_start)
                    new_end = self._minutes_to_time(late_end)
                    
                    suggestions.append({
                        'type': 'reschedule',
                        'start_time': new_start,
                        'end_time': new_end,
                        'description': f"调整到 {new_start}-{new_end}，避开「{conflicting_event['title']}」"
                    })
            
            # 2. 调整到不同的日期
            tomorrow_date = datetime.strptime(event['date'], '%Y-%m-%d').date() + timedelta(days=1)
            tomorrow_str = tomorrow_date.strftime('%Y-%m-%d')
            
            suggestions.append({
                'type': 'next_day',
                'date': tomorrow_str,
                'start_time': event['start_time'],
                'end_time': event['end_time'],
                'description': f"调整到明天 {event['start_time']} 相同时间"
            })
            
            # 3. 查找其他可用时间段
            available_slots = self._find_available_slots(
                event['date'],
                all_events,
                duration,
                preferred_start=event['start_time']
            )
            
            # 添加最多2个可用时间段建议
            for i, slot in enumerate(available_slots[:2]):
                if i == 0:  # 确保第一个建议与上面的不重复
                    if suggestions and suggestions[0]['type'] == 'reschedule':
                        if suggestions[0]['start_time'] == slot['start']:
                            continue
                
                # 确定时间段类型的中文描述
                period_desc = ""
                start_hour = int(slot['start'].split(':')[0])
                if start_hour < 9:
                    period_desc = "早晨"
                elif start_hour < 12:
                    period_desc = "上午"
                elif start_hour < 14:
                    period_desc = "中午"
                elif start_hour < 18:
                    period_desc = "下午"
                else:
                    period_desc = "晚上"
                
                suggestions.append({
                    'type': 'reschedule',
                    'start_time': slot['start'],
                    'end_time': slot['end'],
                    'description': f"调整到{period_desc} {slot['start']} 开始，避开「{conflicting_event['title']}」"
                })
            
            return suggestions
            
        except Exception as e:
            logger.error(f"生成内部冲突建议失败: {str(e)}")
            return []

    # 新增：识别日程类型
    def _identify_event_type(self, event: Dict[str, Any]) -> str:
        """根据日程标题和描述识别日程类型"""
        title = event.get('title', '').lower()
        description = event.get('description', '').lower()
        content = f"{title} {description}"
        
        # 记录日志，便于调试
        logger.info(f"识别日程类型，内容: {content}")
        
        # 遍历所有日程类型，检查关键词匹配
        for event_type, config in self.event_type_preferences.items():
            for keyword in config['keywords']:
                if keyword in content:
                    logger.info(f"识别到日程类型: {event_type}，关键词: {keyword}")
                    return event_type
        
        # 尝试更模糊的匹配
        if '跑' in content or '运动' in content or '锻炼' in content:
            if '早' in content or '晨' in content:
                logger.info("模糊匹配到晨练活动")
                return 'morning_exercise'
            else:
                logger.info("模糊匹配到运动活动")
                return 'workout'
        
        if '课' in content or '学习' in content or '上课' in content:
            logger.info("模糊匹配到课程活动")
            return 'class'
        
        if '吃' in content or '饭' in content or '餐' in content:
            logger.info("模糊匹配到用餐活动")
            return 'meal'
        
        # 根据时间推断类型
        start_time = event.get('start_time', '')
        if start_time:
            try:
                hours = int(start_time.split(':')[0])
                if hours < 8:
                    logger.info("根据时间(早晨)推断为晨练活动")
                    return 'morning_exercise'
                elif hours >= 18:
                    logger.info("根据时间(晚上)推断为健身活动")
                    return 'workout'
                elif 11 <= hours <= 13:
                    logger.info("根据时间(中午)推断为用餐活动")
                    return 'meal'
            except (ValueError, IndexError):
                pass
        
        # 默认返回通用类型
        logger.info("未识别到特定类型，返回通用类型")
        return 'general'
    
    # 新增：获取日程类型的首选时间段
    def _get_preferred_time_slots(self, event_type: str, date_str: str) -> List[Dict[str, Any]]:
        """获取指定日程类型的首选时间段"""
        preferred_slots = []
        
        # 检查是否为周末
        is_weekend = False
        if date_str:
            try:
                date_obj = datetime.strptime(date_str, '%Y-%m-%d').date()
                is_weekend = date_obj.weekday() >= 5  # 5和6是周六和周日
            except ValueError:
                logger.warning(f"日期格式错误: {date_str}")
        
        # 获取日程类型配置
        type_config = self.event_type_preferences.get(event_type)
        if not type_config:
            # 如果没有找到对应类型，返回默认时间段
            return [
                {'start': '09:00', 'end': '10:00', 'description': '上午9点'},
                {'start': '14:00', 'end': '15:00', 'description': '下午2点'},
                {'start': '19:00', 'end': '20:00', 'description': '晚上7点'}
            ]
        
        # 根据首选时间段生成具体时间
        for slot in type_config['preferred_slots']:
            start, end = slot.split('-')
            preferred_slots.append({
                'start': start,
                'end': end,
                'description': f"{self._get_period_description(start)} {start}"
            })
        
        # 根据首选时间段生成更多选项
        for period_name in type_config['preferred_periods']:
            # 跳过周末特定时间段（如果不是周末）
            if not is_weekend and period_name.startswith('weekend_'):
                continue
                
            period = self.time_periods.get(period_name)
            if period:
                start_minutes = self._time_to_minutes(period['start'])
                end_minutes = self._time_to_minutes(period['end'])
                
                # 在时间段内每隔30分钟生成一个选项
                for start_min in range(start_minutes, end_minutes - 60, 30):
                    start_time = self._minutes_to_time(start_min)
                    end_time = self._minutes_to_time(start_min + 60)  # 默认1小时
                    
                    # 检查是否已经添加过这个时间段
                    if not any(slot['start'] == start_time for slot in preferred_slots):
                        preferred_slots.append({
                            'start': start_time,
                            'end': end_time,
                            'description': f"{period['description']} {start_time}"
                        })
        
        return preferred_slots
    
    # 新增：获取时间段描述
    def _get_period_description(self, time_str: str) -> str:
        """根据时间获取时间段描述"""
        minutes = self._time_to_minutes(time_str)
        
        if minutes < self._time_to_minutes('08:00'):
            return '早晨'
        elif minutes < self._time_to_minutes('11:30'):
            return '上午'
        elif minutes < self._time_to_minutes('14:00'):
            return '中午'
        elif minutes < self._time_to_minutes('17:00'):
            return '下午'
        elif minutes < self._time_to_minutes('19:00'):
            return '傍晚'
        else:
            return '晚上'
            
    # 修改：生成智能解决方案
    def generate_conflict_solutions(self, new_event: Dict[str, Any], conflicts: List[Dict[str, Any]], existing_events: List[Dict[str, Any]]) -> List[Dict[str, Any]]:
        """生成智能冲突解决方案"""
        suggestions = []
        
        try:
            # 识别日程类型
            event_type = self._identify_event_type(new_event)
            logger.info(f"日程类型: {event_type}")
            
            # 获取日程持续时间
            start_minutes = self._time_to_minutes(new_event['start_time'])
            end_minutes = self._time_to_minutes(new_event['end_time'])
            duration = end_minutes - start_minutes
            
            # 获取日程日期
            event_date = new_event.get('date', datetime.now().strftime('%Y-%m-%d'))
            
            # 1. 根据日程类型获取首选时间段
            preferred_slots = self._get_preferred_time_slots(event_type, event_date)
            logger.info(f"获取到首选时间段: {len(preferred_slots)}个")
            
            # 2. 检查首选时间段是否有冲突
            valid_slots = []
            for slot in preferred_slots:
                has_conflict = False
                slot_start = self._time_to_minutes(slot['start'])
                slot_end = self._time_to_minutes(slot['end'])
                
                # 调整结束时间以保持原始持续时间
                if duration > 0:
                    slot_end = slot_start + duration
                    slot['end'] = self._minutes_to_time(slot_end)
                
                # 检查是否与现有日程冲突
                for event in existing_events:
                    if str(event.get('date', '')) == str(event_date):
                        event_start = self._time_to_minutes(event['start_time'])
                        event_end = self._time_to_minutes(event['end_time'])
                        
                        # 检查是否有重叠
                        if not (slot_end <= event_start or slot_start >= event_end):
                            has_conflict = True
                            break
                
                if not has_conflict:
                    valid_slots.append(slot)
            
            logger.info(f"有效时间段: {len(valid_slots)}个")
            
            # 3. 为有效时间段生成建议
            type_config = self.event_type_preferences.get(event_type, {})
            type_description = type_config.get('description', '此类活动')
            
            for slot in valid_slots[:3]:  # 最多提供3个建议
                suggestion = {
                    'type': 'type_based',
                    'start_time': slot['start'],
                    'end_time': slot['end'],
                    'description': f"调整到{slot['description']}，适合{type_description}"
                }
                suggestions.append(suggestion)
                logger.info(f"添加基于类型的建议: {suggestion['description']}")
            
            # 4. 特殊处理：如果是运动类活动，考虑早晨或晚上时间段
            if event_type in ['morning_exercise', 'workout', 'sports']:
                # 早晨时间段（适合晨练）
                early_morning_slots = [
                    {'start': '06:00', 'end': '07:00'},
                    {'start': '06:30', 'end': '07:30'},
                    {'start': '07:00', 'end': '08:00'}
                ]
                
                # 晚上时间段（适合健身、运动）
                evening_slots = [
                    {'start': '17:30', 'end': '19:00'},
                    {'start': '19:00', 'end': '20:30'},
                    {'start': '20:00', 'end': '21:30'}
                ]
                
                # 根据活动类型选择合适的时间段
                target_slots = early_morning_slots if event_type == 'morning_exercise' else evening_slots
                
                for slot in target_slots:
                    has_conflict = False
                    slot_start = self._time_to_minutes(slot['start'])
                    slot_end = self._time_to_minutes(slot['end'])
                    
                    # 检查是否与现有日程冲突
                    for event in existing_events:
                        if str(event.get('date', '')) == str(event_date):
                            event_start = self._time_to_minutes(event['start_time'])
                            event_end = self._time_to_minutes(event['end_time'])
                            
                            # 检查是否有重叠
                            if not (slot_end <= event_start or slot_start >= event_end):
                                has_conflict = True
                                break
                    
                    if not has_conflict:
                        period_desc = "早晨" if slot_start < self._time_to_minutes('08:00') else "晚上"
                        activity_desc = "晨练" if event_type == 'morning_exercise' else ("健身" if event_type == 'workout' else "运动")
                        
                        suggestion = {
                            'type': 'activity_specific',
                            'start_time': slot['start'],
                            'end_time': slot['end'],
                            'description': f"调整到{period_desc} {slot['start']}，适合{activity_desc}"
                        }
                        suggestions.append(suggestion)
                        logger.info(f"添加活动特定建议: {suggestion['description']}")
            
            # 5. 特殊处理：如果是学习类活动，考虑图书馆开放时间
            if event_type in ['study', 'library', 'class']:
                library_slots = [
                    {'start': '09:00', 'end': '11:30', 'period': '上午'},
                    {'start': '14:00', 'end': '17:00', 'period': '下午'},
                    {'start': '19:00', 'end': '21:30', 'period': '晚上'}
                ]
                
                for slot in library_slots:
                    has_conflict = False
                    slot_start = self._time_to_minutes(slot['start'])
                    slot_end = self._time_to_minutes(slot['end'])
                    
                    # 调整结束时间以保持原始持续时间
                    if duration > 0 and duration < (slot_end - slot_start):
                        slot_end = slot_start + duration
                        slot['end'] = self._minutes_to_time(slot_end)
                    
                    # 检查是否与现有日程冲突
                    for event in existing_events:
                        if str(event.get('date', '')) == str(event_date):
                            event_start = self._time_to_minutes(event['start_time'])
                            event_end = self._time_to_minutes(event['end_time'])
                            
                            # 检查是否有重叠
                            if not (slot_end <= event_start or slot_start >= event_end):
                                has_conflict = True
                                break
                    
                    if not has_conflict:
                        suggestion = {
                            'type': 'activity_specific',
                            'start_time': slot['start'],
                            'end_time': slot['end'],
                            'description': f"调整到{slot['period']}学习时间 {slot['start']}"
                        }
                        suggestions.append(suggestion)
                        logger.info(f"添加学习时间建议: {suggestion['description']}")
            
            # 6. 特殊处理：如果是社交类活动，考虑用餐时间
            if event_type in ['social', 'meal']:
                meal_slots = [
                    {'start': '11:30', 'end': '13:00', 'period': '午餐'},
                    {'start': '17:30', 'end': '19:00', 'period': '晚餐'}
                ]
                
                for slot in meal_slots:
                    has_conflict = False
                    slot_start = self._time_to_minutes(slot['start'])
                    slot_end = self._time_to_minutes(slot['end'])
                    
                    # 检查是否与现有日程冲突
                    for event in existing_events:
                        if str(event.get('date', '')) == str(event_date):
                            event_start = self._time_to_minutes(event['start_time'])
                            event_end = self._time_to_minutes(event['end_time'])
                            
                            # 检查是否有重叠
                            if not (slot_end <= event_start or slot_start >= event_end):
                                has_conflict = True
                                break
                    
                    if not has_conflict:
                        suggestion = {
                            'type': 'meal_time',
                            'start_time': slot['start'],
                            'end_time': slot['end'],
                            'description': f"调整到{slot['period']}时间 {slot['start']}"
                        }
                        suggestions.append(suggestion)
                        logger.info(f"添加用餐时间建议: {suggestion['description']}")
            
            # 7. 添加其他通用建议
            
            # 7.1 调整到第二天相同时间
            tomorrow_date = datetime.strptime(event_date, '%Y-%m-%d').date() + timedelta(days=1)
            tomorrow_str = tomorrow_date.strftime('%Y-%m-%d')
            
            # 检查明天是否有冲突
            tomorrow_conflicts = False
            for event in existing_events:
                if str(event.get('date', '')) == tomorrow_str and \
                self._time_overlap(
                    {'start_time': new_event['start_time'], 'end_time': new_event['end_time']}, 
                    event
                ):
                    tomorrow_conflicts = True
                    break
            
            if not tomorrow_conflicts:
                suggestion = {
                    'type': 'next_day',
                    'date': tomorrow_str,
                    'start_time': new_event['start_time'],
                    'end_time': new_event['end_time'],
                    'description': f"调整到明天 {new_event['start_time']} 相同时间"
                }
                suggestions.append(suggestion)
                logger.info(f"添加次日建议: {suggestion['description']}")
            
            # 7.2 如果是短时间活动，考虑缩短时间
            if duration <= 90:  # 90分钟以内的活动
                for conflict in conflicts:
                    overlap = self._get_conflict_duration(new_event, conflict)
                    
                    # 如果重叠不超过日程时长的一半，可以考虑缩短
                    if overlap <= duration / 2:
                        conflict_start = self._time_to_minutes(conflict['start_time'])
                        new_start = self._time_to_minutes(new_event['start_time'])
                        
                        # 提前结束
                        if new_start < conflict_start:
                            new_end = self._minutes_to_time(conflict_start)
                            actual_duration = conflict_start - new_start
                            suggestion = {
                                'type': 'shorten',
                                'start_time': new_event['start_time'],
                                'end_time': new_end,
                                'description': f"提前在 {new_end} 结束，持续{actual_duration//60}小时{actual_duration%60}分钟，避开「{conflict['title']}」"
                            }
                            suggestions.append(suggestion)
                            logger.info(f"添加缩短时间建议: {suggestion['description']}")
            
            # 8. 去重并限制建议数量
            unique_suggestions = []
            suggestion_keys = set()
            
            # 首先添加基于活动类型的建议
            for suggestion in suggestions:
                if suggestion['type'] in ['type_based', 'activity_specific']:
                    key = f"{suggestion.get('start_time')}-{suggestion.get('end_time')}"
                    if key not in suggestion_keys:
                        suggestion_keys.add(key)
                        unique_suggestions.append(suggestion)
            
            # 然后添加其他类型的建议
            for suggestion in suggestions:
                if suggestion['type'] not in ['type_based', 'activity_specific']:
                    key = f"{suggestion.get('start_time')}-{suggestion.get('end_time')}"
                    if key not in suggestion_keys:
                        suggestion_keys.add(key)
                        unique_suggestions.append(suggestion)
                        
                    # 最多返回5个建议
                    if len(unique_suggestions) >= 5:
                        break
            
            logger.info(f"最终生成 {len(unique_suggestions)} 个建议")
            return unique_suggestions
            
        except Exception as e:
            logger.exception(f"生成智能冲突解决方案失败: {str(e)}")
            return [] 